<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-card class="app-card" :body-style="{ padding: '24px' }">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" class="search-form">
        <el-form-item label="到期日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="search-input date-range-picker"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="queryParams.product_id" placeholder="请选择产品" clearable class="search-input">
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.product_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="search-button" @click="handleQuery">查询</el-button>
          <el-button class="reset-button" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表区域 -->
    <el-card class="app-card" :body-style="{ padding: '24px' }">
      <div class="table-header">
        <div class="left-buttons">
          <!-- 左侧工具栏按钮 -->
          <el-button type="primary" class="action-button batch-button" :disabled="selectedExpirations.length === 0" @click="handleBatchAction">
            <el-icon class="button-icon"><operation /></el-icon>批量操作
          </el-button>
        </div>
        <div class="right-buttons">
          <el-button type="success" class="action-button export-button" @click="handleExport">
            <el-icon class="button-icon"><download /></el-icon>导出
          </el-button>
          <el-button type="primary" class="action-button import-button" @click="openImportDialog">
            <el-icon class="button-icon"><upload /></el-icon>导入
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="expirationList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        class="data-table"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="expiration_date" label="到期月份" width="120">
          <template #default="scope">
            {{ scope.row.expiration_date ? formatExpirationMonth(scope.row.expiration_date) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="product_name_display" label="到期产品" width="150" />
        <el-table-column prop="expiration_date" label="到期日期" width="120" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column prop="order_number" label="订单号" width="150" />
        <el-table-column prop="customer_name_display" label="客户名称" width="150" />
        <el-table-column prop="authorized_domain" label="授权域名" width="180" show-overflow-tooltip />
        <el-table-column prop="order_date" label="下单日期" width="120" />
        <el-table-column prop="purchase_years_display" label="购买年限" width="100" />
        <el-table-column prop="activation_date" label="激活日期" width="120" />
        <el-table-column prop="nickname_display" label="激活人" width="120" />
        <el-table-column prop="order_status_display" label="激活状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.order_status === 1 ? 'success' : 'warning'"
              class="status-tag"
            >
              {{ scope.row.order_status_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="order_amount" label="订单金额" width="100" />
      </el-table>
      
      <div class="table-pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total || 100"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
      
    </el-card>
    
    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入产品到期数据"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      append-to-body
    >
      <el-alert
        type="info"
        :closable="false"
        class="import-alert"
      >
        <template #title>
          <div class="alert-title">
            <strong>导入说明</strong>
          </div>
        </template>
        <div class="alert-content">
          <p>1. 请先下载导入模板，按模板格式填写数据</p>
          <p>2. 只支持 .xlsx 或 .xls 格式的Excel文件</p>
          <p>3. 文件大小不能超过10MB</p>
        </div>
      </el-alert>
      
      <div class="import-actions">
        <el-button 
          type="primary" 
          plain 
          size="large" 
          @click="downloadImportTemplate"
        >
          <el-icon><download /></el-icon>
          下载导入模板
        </el-button>
      </div>
      
      <el-divider content-position="center">选择文件上传</el-divider>
      
      <el-form ref="importFormRef" :model="importForm" :rules="importRules" label-width="0">
        <el-form-item prop="file">
          <el-upload
            ref="uploadRef"
            class="import-upload"
            action="#"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
            :on-remove="handleFileRemove"
            accept=".xlsx,.xls"
            :file-list="fileList"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只支持 .xlsx 或 .xls 格式的Excel文件，文件大小不能超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitImport"
            :loading="importLoading"
            :disabled="!selectedFile"
          >
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getExpirationList, exportExpirations, getExpirationImportTemplate, importExpirations } from '@/api/expirations';
import { getProductList } from '@/api/products';
import { Download, Operation, Upload, UploadFilled } from '@element-plus/icons-vue';

// 日期范围选择器
const dateRange = ref([]);

// 查询参数
const queryParams = reactive({
  product_id: null,
  page: 1,
  page_size: 10,
  ordering: 'days_to_expiration' // 默认按到期日期接近程度排列（近的在前）
});

// 表格数据
const expirationList = ref([]);
const loading = ref(false);
const productOptions = ref([]);
const selectedExpirations = ref([]);

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 导入相关
const importDialogVisible = ref(false);
const importLoading = ref(false);
const uploadRef = ref(null);
const importFormRef = ref(null);
const fileList = ref([]);
const selectedFile = ref(null);
const importForm = reactive({
  file: null
});
const importRules = {
  file: [{ required: true, message: '请选择要导入的文件', trigger: 'change' }]
};

// 初始化
onMounted(() => {
  // 设置默认分页数据
  pagination.total = 100; // 设置默认总数
  pagination.page = 1;
  pagination.pageSize = 10;
  
  // 加载数据
  getList();
  loadProductOptions();
});

// 获取到期产品列表
const getList = async () => {
  loading.value = true;
  try {
    // 构建请求参数，处理日期范围
    const params = { ...queryParams };
    if (dateRange.value && dateRange.value.length === 2) {
      params.expiration_date_start = dateRange.value[0];
      params.expiration_date_end = dateRange.value[1];
    }
    
    // 添加分页
    params.page = pagination.page;
    params.page_size = pagination.pageSize;
    
    const response = await getExpirationList(params);
    
    // 调试输出，查看响应结构
    console.log('API响应数据结构:', response);
    
    // 处理标准 API 响应结构
    let data = response;
    
    // 检查是否是嵌套的数据格式 {code, message, data}
    if (response && response.code === 200 && response.data) {
      data = response.data;
      console.log('使用嵌套数据结构:', data);
    }
    
    // 设置列表数据
    expirationList.value = data.results || [];
    
    // 更新分页总数
    if (data && typeof data.count === 'number') {
      pagination.total = data.count;
    }
    
    // 调试输出更详细的信息
    console.log('解析后的列表数据:', expirationList.value);
    console.log('分页信息:', {
      total: pagination.total,
      page: pagination.page,
      pageSize: pagination.pageSize,
    });
    
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败: ' + (error.message || '未知错误'));
    expirationList.value = []; // 出错时清空列表
  } finally {
    loading.value = false;
  }
};

// 获取产品选项
const loadProductOptions = async () => {
  try {
    const response = await getProductList();
    productOptions.value = response.results || [];
  } catch (error) {
    console.error(error);
  }
};

// 格式化到期月份
const formatExpirationMonth = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
};

// 处理排序变化
const handleSortChange = (column) => {
  if (!column.prop || !column.order) {
    queryParams.ordering = 'days_to_expiration'; // 默认排序，即将到期的在前面
  } else if (column.prop === 'expiration_date') {
    // 特殊处理expiration_date列的排序
    if (column.order === 'ascending') {
      // 升序：从早到晚
      queryParams.ordering = 'expiration_date';
    } else {
      // 降序：从晚到早
      queryParams.ordering = '-expiration_date';
    }
  } else {
    // 其他列的常规排序
    const prefix = column.order === 'descending' ? '-' : '';
    queryParams.ordering = `${prefix}${column.prop}`;
  }
  getList();
};

// 处理查询
const handleQuery = () => {
  pagination.page = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  dateRange.value = [];
  queryParams.product_id = null;
  queryParams.ordering = 'days_to_expiration'; // 重置为默认排序，即将到期的在前面
  handleQuery();
};

// 处理导出
const handleExport = async () => {
  try {
    // 显示加载提示
    const loadingInstance = ElMessage({
      message: '正在准备导出数据，请稍候...',
      type: 'info',
      duration: 0 // 持续显示直到手动关闭
    });
    
    // 构建导出参数，处理日期范围
    const params = { ...queryParams };
    if (dateRange.value && dateRange.value.length === 2) {
      params.expiration_date_start = dateRange.value[0];
      params.expiration_date_end = dateRange.value[1];
    }
    
    const response = await exportExpirations(params);
    
    // 关闭加载提示
    loadingInstance.close();
    
    // 检查响应类型
    if (!(response instanceof Blob)) {
      console.error('导出返回的不是Blob数据:', response);
      ElMessage.error('导出失败: 服务器返回格式错误');
      return;
    }
    
    // 验证Blob内容是否有效
    if (response.size === 0) {
      ElMessage.error('导出失败: 返回的文件内容为空');
      return;
    }
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(response); // 直接使用response，无需再次创建Blob
    link.download = `产品到期数据_${new Date().toISOString().slice(0,10)}.xlsx`;
    document.body.appendChild(link);
    link.click();
    
    // 延迟移除链接，确保下载开始
    setTimeout(() => {
      document.body.removeChild(link); 
      URL.revokeObjectURL(link.href); // 释放内存
    }, 100);
    
    ElMessage.success('导出成功');
  } catch (error) {
    // 关闭可能存在的加载提示
    ElMessage.closeAll('info');
    
    console.error('导出数据失败:', error);
    
    // 尝试从错误对象中获取更多信息
    let errorMessage = '导出失败';
    if (error.response) {
      if (error.response.data instanceof Blob) {
        try {
          // 尝试从Blob中读取错误信息
          const text = await error.response.data.text();
          const errorData = JSON.parse(text);
          errorMessage = errorData.message || '服务器返回了错误';
        } catch (e) {
          errorMessage = '导出失败: 无法解析服务器错误';
        }
      } else if (error.response.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.response.statusText) {
        errorMessage = `导出失败: ${error.response.statusText}`;
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    ElMessage.error(errorMessage);
  }
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  getList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.page = val;
  getList();
};

// 处理选中行变化
const handleSelectionChange = (selection) => {
  selectedExpirations.value = selection;
};

// 批量操作
const handleBatchAction = () => {
  if (selectedExpirations.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  ElMessage.success(`已选择 ${selectedExpirations.value.length} 条记录，可以进行批量操作`);
  // 这里可以添加具体的批量操作逻辑
};

// 打开导入对话框
const openImportDialog = () => {
  importDialogVisible.value = true;
};

// 下载导入模板
const downloadImportTemplate = async () => {
  try {
    // 显示加载提示
    const loadingInstance = ElMessage({
      message: '正在准备模板文件，请稍候...',
      type: 'info',
      duration: 0 // 持续显示直到手动关闭
    });
    
    const response = await getExpirationImportTemplate();
    
    // 关闭加载提示
    loadingInstance.close();
    
    // 检查响应类型
    if (!(response instanceof Blob)) {
      console.error('下载模板返回的不是Blob数据:', response);
      ElMessage.error('下载模板失败: 服务器返回格式错误');
      return;
    }
    
    // 验证Blob内容是否有效
    if (response.size === 0) {
      ElMessage.error('下载模板失败: 返回的文件内容为空');
      return;
    }
    
    // 创建Blob链接并下载
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `产品到期数据导入模板_${new Date().toISOString().slice(0,10)}.xlsx`;
    document.body.appendChild(link); // 添加到DOM以确保在所有浏览器中工作
    link.click();
    
    // 延迟移除链接，确保下载开始
    setTimeout(() => {
      document.body.removeChild(link); 
      URL.revokeObjectURL(link.href); // 释放内存
    }, 100);
    
    ElMessage.success('下载模板成功');
  } catch (error) {
    // 关闭可能存在的加载提示
    ElMessage.closeAll('info');
    
    console.error('下载模板失败:', error);
    
    // 尝试从错误对象中获取更多信息
    let errorMessage = '下载模板失败';
    if (error.response) {
      if (error.response.data instanceof Blob) {
        try {
          // 尝试从Blob中读取错误信息
          const text = await error.response.data.text();
          const errorData = JSON.parse(text);
          errorMessage = errorData.message || '服务器返回了错误';
        } catch (e) {
          errorMessage = '下载模板失败: 无法解析服务器错误';
        }
      } else if (error.response.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.response.statusText) {
        errorMessage = `下载模板失败: ${error.response.statusText}`;
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    ElMessage.error(errorMessage);
  }
};

// 处理文件变化
const handleFileChange = (file) => {
  // 检查文件类型
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel' ||
                  file.name.endsWith('.xlsx') || 
                  file.name.endsWith('.xls');
                  
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件! (.xlsx, .xls)');
    uploadRef.value.handleRemove(file);
    return false;
  }
  
  // 检查文件大小 (10MB)
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    uploadRef.value.handleRemove(file);
    return false;
  }
  
  selectedFile.value = file;
  return true;
};

// 处理文件超出限制
const handleExceed = (files) => {
  ElMessage.warning('只能上传1个文件!');
  // 替换文件
  if (uploadRef.value && files.length > 0) {
    uploadRef.value.clearFiles();
    selectedFile.value = null;
    setTimeout(() => {
      uploadRef.value.handleStart(files[0]);
    }, 10);
  }
};

// 处理文件移除
const handleFileRemove = () => {
  selectedFile.value = null;
};

// 提交导入
const submitImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }
  
  try {
    importLoading.value = true;
    const formData = new FormData();
    formData.append('file', selectedFile.value.raw, selectedFile.value.name);
    
    // 发送导入请求
    const res = await importExpirations(formData);
    console.log('导入响应:', res);
    
    // 处理响应
    if (res.code === 200) {
      // 显示导入成功信息
      const successCount = res.data?.success_count || 0;
      const errorCount = res.data?.error_count || 0;
      
      if (errorCount > 0) {
        // 有错误记录，显示成功导入但有部分错误
        ElMessage({
          message: `成功导入${successCount}条记录，有${errorCount}条记录导入失败`,
          type: 'warning',
          duration: 5000
        });
        
        // 可以考虑显示错误详情
        console.log('导入错误详情:', res.data?.errors);
      } else {
        // 全部成功
        ElMessage.success(`成功导入${successCount}条记录`);
      }
      
      // 关闭导入对话框
      importDialogVisible.value = false;
      
      // 重置上传状态
      fileList.value = [];
      selectedFile.value = null;
      
      // 刷新列表
      getList();
    } else {
      // 导入失败
      ElMessage.error(res.message || '导入失败');
    }
  } catch (error) {
    console.error('导入到期产品失败:', error);
    
    // 尝试从错误对象中获取更多信息
    let errorMessage = '导入失败';
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMessage = error.response.data.message;
      } else if (error.response.data.code) {
        errorMessage = `导入失败 (错误代码: ${error.response.data.code})`;
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    ElMessage.error(errorMessage);
  } finally {
    importLoading.value = false;
  }
};
</script>

<style scoped>
.app-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  height: auto;
  padding: 20px;
  box-sizing: border-box;
}

.app-card {
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  border: none;
  overflow: visible;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.search-input {
  width: 220px;
  border-radius: 8px;
}

.search-button, .reset-button {
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.search-button {
  background-color: #0071e3;
  border-color: #0071e3;
}

.search-button:hover {
  background-color: #0077ed;
  border-color: #0077ed;
  transform: translateY(-1px);
}

.reset-button {
  color: #606266;
  background-color: #f5f7fa;
  border-color: #f5f7fa;
}

.reset-button:hover {
  background-color: #e4e7ed;
  border-color: #e4e7ed;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  width: 100%;
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.action-button {
  border-radius: 8px;
  padding: 10px 16px;
  height: 40px;
  font-weight: 500;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.batch-button {
  background-color: #0071e3;
  border-color: #0071e3;
}

.export-button {
  background-color: #67c23a;
  border-color: #67c23a;
}

.import-button {
  background-color: #0071e3;
  border-color: #0071e3;
}

.action-button:hover {
  transform: translateY(-1px);
}

.button-icon {
  margin-right: 6px;
}

.data-table {
  border-radius: 8px;
  border: 1px solid #ebeef5;
  margin-bottom: 30px;
  width: 100%;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--border) {
  border-radius: 8px;
  overflow: hidden;
}

.status-tag {
  border-radius: 20px;
  padding: 2px 10px;
  font-size: 12px;
}

.table-pagination {
  margin-top: 24px;
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination {
  --el-pagination-button-bg-color: #f5f7fa;
  --el-pagination-hover-color: #0071e3;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #0071e3;
}

.import-alert {
  margin-bottom: 20px;
}

.alert-title {
  font-weight: 600;
}

.alert-content {
  margin-top: 10px;
}

.import-actions {
  margin-bottom: 20px;
}

.import-upload {
  width: 100%;
}

.dialog-footer {
  text-align: right;
}

.date-range-picker {
  width: 360px !important;
}
</style> 